﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 车辆品牌表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppVehicleBrandService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppVehicleBrand> _appVehicleBrandRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public AppVehicleBrandService(SqlSugarRepository<AppVehicleBrand> appVehicleBrandRep, ISqlSugarClient sqlSugarClient)
    {
        _appVehicleBrandRep = appVehicleBrandRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询车辆品牌表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询车辆品牌表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppVehicleBrandOutput>> Page(PageAppVehicleBrandInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appVehicleBrandRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Name.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(input.LogoUrl != null, u => u.LogoUrl == input.LogoUrl)
            .WhereIF(input.Sort != null, u => u.Sort == input.Sort)
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status)
            .LeftJoin<SysFile>((u, logoUrl) => u.LogoUrl == logoUrl.Id)
            .Select((u, logoUrl) => new AppVehicleBrandOutput
            {
                Id = u.Id,
                Name = u.Name,
                LogoUrl = u.LogoUrl,
                LogoUrlFkDisplayName = $"{logoUrl.FileName}",
                Sort = u.Sort,
                Status = u.Status,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取车辆品牌表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取车辆品牌表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppVehicleBrand> Detail([FromQuery] QueryByIdAppVehicleBrandInput input)
    {
        return await _appVehicleBrandRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取所有车辆品牌表 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [DisplayName("获取所有车辆品牌表")]
    [ApiDescriptionSettings(Name = "List"), HttpGet]
    public async Task<List<AppVehicleBrand>> List()
    {
        return await _appVehicleBrandRep.GetListAsync();
    }

    /// <summary>
    /// 增加车辆品牌表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加车辆品牌表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppVehicleBrandInput input)
    {
        var entity = input.Adapt<AppVehicleBrand>();
        return await _appVehicleBrandRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新车辆品牌表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新车辆品牌表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppVehicleBrandInput input)
    {
        var entity = input.Adapt<AppVehicleBrand>();
        await _appVehicleBrandRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除车辆品牌表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除车辆品牌表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppVehicleBrandInput input)
    {
        var entity = await _appVehicleBrandRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appVehicleBrandRep.FakeDeleteAsync(entity);   //假删除
        //await _appVehicleBrandRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除车辆品牌表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除车辆品牌表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppVehicleBrandInput> input)
    {
        var exp = Expressionable.Create<AppVehicleBrand>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appVehicleBrandRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appVehicleBrandRep.FakeDeleteAsync(list);   //假删除
        //return await _appVehicleBrandRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 设置车辆品牌表状态 🚫
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置车辆品牌表状态")]
    [ApiDescriptionSettings(Name = "SetStatus"), HttpPost]
    public async Task SetAppVehicleBrandStatus(SetAppVehicleBrandStatusInput input)
    {
        await _appVehicleBrandRep.AsUpdateable().SetColumns(u => u.Status, input.Status).Where(u => u.Id == input.Id).ExecuteCommandAsync();
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppVehicleBrandInput input)
    {
        var logoUrlData = await _appVehicleBrandRep.Context.Queryable<SysFile>()
            .InnerJoinIF<AppVehicleBrand>(input.FromPage, (u, r) => u.Id == r.LogoUrl)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.FileName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "logoUrl", logoUrlData },
        };
    }
    
    /// <summary>
    /// 导出车辆品牌表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出车辆品牌表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppVehicleBrandInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppVehicleBrandOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "车辆品牌表导出记录");
    }
    
    /// <summary>
    /// 下载车辆品牌表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载车辆品牌表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppVehicleBrandOutput>(), "车辆品牌表导入模板", (_, info) =>
        {
            if (nameof(ExportAppVehicleBrandOutput.LogoUrlFkDisplayName) == info.Name) return _appVehicleBrandRep.Context.Queryable<SysFile>().Select(u => $"{u.FileName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入车辆品牌表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入车辆品牌表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppVehicleBrandInput, AppVehicleBrand>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 品牌Logo
                    var logoUrlLabelList = pageItems.Where(x => x.LogoUrlFkDisplayName != null).Select(x => x.LogoUrlFkDisplayName).Distinct().ToList();
                    if (logoUrlLabelList.Any()) {
                        var logoUrlLinkMap = _appVehicleBrandRep.Context.Queryable<SysFile>().Where(u => logoUrlLabelList.Contains($"{u.FileName}")).ToList().ToDictionary(u => $"{u.FileName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.LogoUrl = logoUrlLinkMap.GetValueOrDefault(e.LogoUrlFkDisplayName ?? "");
                            if (e.LogoUrl == null) e.Error = "品牌Logo链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Sort == null){
                            x.Error = "排序不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Status == null){
                            x.Error = "状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppVehicleBrand>>();
                    
                    var storageable = _appVehicleBrandRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Name), "品牌名称不能为空")
                        .SplitError(it => it.Item.Name?.Length > 50, "品牌名称长度不能超过50个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
